package com.hoshiicloud.user.service.impl.usercenter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.user.entity.usercenter.MemberAddress;
import com.hoshiicloud.user.entity.usercenter.PlatConsumer;
import com.hoshiicloud.user.feign.IdGeneratorService;
import com.hoshiicloud.user.mapper.usercenter.MemberAddressMapper;
import com.hoshiicloud.user.service.usercenter.IMemberAddressService;
import com.hoshiicloud.user.service.usercenter.IPlatConsumerService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户账户Service接口实现类
 *
 * @author : yangcheng
 * @date : 2019/5/11 10:44
 * @mail : maiboyc@163.com
 **/
@Service
public class MemberAddressServiceImpl extends ServiceImpl<MemberAddressMapper, MemberAddress> implements IMemberAddressService {

    // ID生成Service
    @Autowired
    private IdGeneratorService idGeneratorService;

    // 用户基本信息Service
    @Autowired
    private IPlatConsumerService platMemberService;

    /**
     * 根据id获取
     * @param id ID
     * @return MemberAddress
     */
    @Cacheable(cacheNames = "memberAddress", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "用户管理-用户收货地址管理-根据ID查询用户收货地址")
    @Override
    public MemberAddress getById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 根据一组id
     * @param ids id组
     * @return List<MemberAddress>
     */
    @Cacheable(cacheNames = "memberAddress", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#ids")
    @Logable(authName = "用户管理-用户收货地址管理-根据ID组查询用户收货地址")
    @Override
    public List<MemberAddress> getByIds(List<Long> ids) {
        return baseMapper.selectBatchIds(ids);
    }

    /**
     * 保存
     * @param entity 实体对象
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "memberAddress", allEntries = true)
    @Logable(authName = "用户管理-用户收货地址管理-新增用户收货地址")
    @Override
    public Long insert(MemberAddress entity) throws ServiceException {
        // 调用主键生成微服务生成主键
        String id = idGeneratorService.queryGeneratorId();
        if (id == null) {
            throw new ServiceException(CommonError.error("新增用户收货地址失败,生成ID主键失败"));
        }
        // 调用用户基本信息Service检查用户账户信息是否存在
        PlatConsumer platConsumer = platMemberService.getById(entity.getUserId());
        if (platConsumer == null) {
            throw new ServiceException(CommonError.error("新增用户收货地址失败，没有找到对应的用户基本信息"));
        }
        // 自动生成id，创建日期 修改日期 创建人 修改人 删除标识
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setCreatedBy("admin");// 需要拿当前的登录人
        entity.setUpdatedBy("admin");// 需要拿当前的登录人
        entity.setDeleted(0);
        int row = baseMapper.insert(entity);
        if (row <= 0) {// 新增失败
            throw new ServiceException(CommonError.error("新增用户收货地址失败"));
        } else {// 新增成功
            // 这里需要判断当前收货地址有没有设置为默认(0-非默认，1-默认)，如果设置为默认，需要将该用户的其他地址设置为非默认，如果没设置保持不变
            if (1 == entity.getDefAddress()) {
                List<MemberAddress> list = getMemberAddresses(entity);
                if (CollectionUtils.isNotEmpty(list)) {
                    list.forEach(item ->{
                        if (!(entity.getId().equals(item.getId()))) {
                            item.setDefAddress(0);
                            update(item);
                        }
                    });
                }
            }
        }
        return entity.getId();
    }

    /**
     * 修改
     * @param entity 实体对象
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "memberAddress", allEntries = true)
    @Logable(authName = "用户管理-用户收货地址管理-修改用户收货地址")
    @Override
    public Long update(MemberAddress entity) throws ServiceException {
        // 自动填入修改时间 修改人
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setUpdatedBy("admin");// 需要拿当前的登录人
        int row = baseMapper.updateById(entity);
        if (row <= 0) {// 修改失败
            throw new ServiceException(CommonError.error("修改用户收货地址失败"));
        } else {// 修改成功
            // 这里需要判断当前收货地址有没有设置为默认(0-非默认，1-默认)，如果设置为默认，需要将该用户的其他地址设置为非默认，如果没设置保持不变
            if (1 == entity.getDefAddress()) {
                List<MemberAddress> list = getMemberAddresses(entity);
                if (CollectionUtils.isNotEmpty(list)) {
                    list.forEach(item ->{
                        if (!(entity.getId().equals(item.getId()))) {
                            item.setDefAddress(0);
                            update(item);
                        }
                    });
                }
            }
        }
        return entity.getId();
    }

    /**
     * 查询
     * @param entity 查询参数实体
     * @return IPage<MemberAddress>
     */
    @Cacheable(cacheNames = "memberAddress", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#entity.pageIndex+':'+#entity.pageSize+':'+#entity.userId+':'+#entity.name+':'+#entity.idCard+':'+#entity.idCard+':'+#entity.phone+':'+#entity.telephone+':'+#entity.postcode")
    @Logable(authName = "用户管理-用户收货地址管理-分页查询用户收货地址")
    @Override
    public IPage<MemberAddress> List(MemberAddress entity) {
        QueryWrapper<MemberAddress> queryWrapper = new QueryWrapper();
        IPage<MemberAddress> page = new Page();
        if (null != entity.getPageIndex()) {
            page.setCurrent(entity.getPageIndex());
        }
        if (null != entity.getPageSize()) {
            page.setSize(entity.getPageSize());
        }
        if (null != entity.getUserId()) {
            queryWrapper.eq("user_id", entity.getUserId());
        }
        if (StringUtils.isNotEmpty(entity.getName())) {
            queryWrapper.like("name", entity.getName());
        }
        if (StringUtils.isNotEmpty(entity.getIdCard())) {
            queryWrapper.like("id_card", entity.getIdCard());
        }
        if (StringUtils.isNotEmpty(entity.getPhone())) {
            queryWrapper.like("phone", entity.getPhone());
        }
        if (StringUtils.isNotEmpty(entity.getTelephone())) {
            queryWrapper.like("telephone", entity.getTelephone());
        }
        if (StringUtils.isNotEmpty(entity.getPostcode())) {
            queryWrapper.like("postcode", entity.getPostcode());
        }
        // 默认查询只查询未逻辑删除的数据
        queryWrapper.eq("deleted", 0);
        return baseMapper.selectPage(page,queryWrapper);
    }

    /**
     * 根据消费者id查找消费者收货地址
     * @param entity 查询参数
     * @return IPage<MemberAddress>
     */
    @Cacheable(cacheNames = "memberAddress", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#entity.userId")
    @Logable(authName = "用户管理-用户收货地址管理-根据查询参数查询用户收货地址信息")
    @Override
    public List<MemberAddress> getMemberAddresses(MemberAddress entity) {
        QueryWrapper<MemberAddress> queryWrapper = new QueryWrapper();
        // 用户ID
        if (entity.getUserId() != null) {
            queryWrapper.eq("user_id", entity.getUserId());
        }
        // 默认查询只查询未逻辑删除的数据
        queryWrapper.eq("deleted", 0);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 删除
     * @param id ID
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "memberAddress", allEntries = true)
    @Logable(authName = "用户管理-用户收货地址管理-删除用户收货地址")
    @Override
    public Long delete(Long id) throws ServiceException {
        MemberAddress entity = this.getById(id);
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除用户收货地址失败"));
        } else {
            return entity.getId();
        }
    }

}